var http = require('http')
var createHandler = require('github-webhook-handler');
const { exec } = require('child_process');
var handler = createHandler({ path: '/', secret: 'ValphaRememberForever' })
// 上面的 secret 保持和 GitHub 后台设置的一致

function run_cmd(cmd, args, callback) {
  var spawn = require('child_process').spawn;
  var child = spawn(cmd, args);
  var resp = "";

  child.stdout.on('data', function (buffer) { resp += buffer.toString(); });
  child.stdout.on('end', function () { callback(resp) });
}

http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404
    res.end('no such location')
  })
}).listen(7777)

handler.on('error', function (err) {
  console.error('Error:', err.message)
})

handler.on('push', function (event) {
  console.log('Received a push event for %s to %s',
    event.payload.repository.name,
    event.payload.ref);
  // run_cmd('sh', ['/scripts/deploy.sh'], function (text) { console.log(text) });

  require('child_process').exec(`/scripts/deploy.sh`,(error, stdout, stderr) => {
    if (error) {
      console.error(`执行的错误: ${error}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
    console.error(`stderr: ${stderr}`);
  } )
})

handler.on('ping', function (event) {
  console.log('Received a ping event for %s to %s',
    event.payload.repository.name,
    event.payload.ref);

  clone_url = event.payload.repository.clone_url
  ssh_url = event.payload.repository.ssh_url
  dir_name = event.payload.repository.full_name
  // run_cmd('/scripts/init_repo.sh', [dir_name, ssh_url], function (text) {
  //   console.log(text)
  // })

  require('child_process').exec(`/scripts/init_repo.sh ${dir_name} ${ssh_url}`,(error, stdout, stderr) => {
    if (error) {
      console.error(`执行的错误: ${error}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
    console.error(`stderr: ${stderr}`);
  } )



})

/*
var http = require('http')
var createHandler = require('github-webhook-handler')
var handler = createHandler({ path: '/hexo-webhook', secret: 'ValphaRememberForever' })

http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404
    res.end('no such location')
  })
}).listen(7777)

handler.on('error', function (err) {
  console.error('Error:', err.message)
})

handler.on('push', function (event) {
  console.log('Received a push event for %s to %s',
    event.payload.repository.name,
    event.payload.ref)
})

handler.on('issues', function (event) {
  console.log('Received an issue event for %s action=%s: #%d %s',
    event.payload.repository.name,
    event.payload.action,
    event.payload.issue.number,
    event.payload.issue.title)
})
 */